package com.fqgj.xjd.user.service.impl;
/**
 * Created by zhangxingyun on 17/7/23.
 */

import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.exception.enums.BasicErrorCodeEnum;
import com.fqgj.xjd.user.client.UserContactService;
import com.fqgj.xjd.user.client.enums.AppCodeEnum;
import com.fqgj.xjd.user.client.enums.UserContactFamilyTypeEnum;
import com.fqgj.xjd.user.client.enums.UserContactFriendTypeEnum;
import com.fqgj.xjd.user.client.request.Carrier;
import com.fqgj.xjd.user.client.request.UserContactAddressBookPageQueryRO;
import com.fqgj.xjd.user.client.request.UserEmergencyContact;
import com.fqgj.xjd.user.client.request.UserSmsPageQueryRO;
import com.fqgj.xjd.user.client.response.*;
import com.fqgj.xjd.user.common.enums.UserErrorCodeEnum;
import com.fqgj.xjd.user.dao.UserContactAddressBookDao;
import com.fqgj.xjd.user.dao.UserContactCarrierDao;
import com.fqgj.xjd.user.dao.UserContactEmergencyDao;
import com.fqgj.xjd.user.dao.UserSmsInfoDao;
import com.fqgj.xjd.user.entity.UserContactAddressBookEntity;
import com.fqgj.xjd.user.entity.UserContactCarrierEntity;
import com.fqgj.xjd.user.entity.UserContactEmergencyEntity;
import com.fqgj.xjd.user.entity.UserSmsInfoEntity;
import com.google.common.collect.Lists;
import com.qianli.common.enums.AppEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @ClassName:
 * @Description: 用户社交信息服务
 * @Author zhangxingyun
 * @Create 2017-07-23 21:18
 */
@Service("userContactService")
public class UserContactServiceImpl implements UserContactService {

    @Autowired
    private UserContactCarrierDao userContactCarrierDao;

    @Autowired
    private UserContactAddressBookDao userContactAddressBookDao;

    @Autowired
    private UserContactEmergencyDao userContactEmergencyDao;

    @Autowired
    private UserSmsInfoDao userSmsInfoDao;

    @Override
    public Response<Boolean> addUserCarrier(String userCode, Carrier carrier) {
        List<UserContactCarrierEntity> entities = userContactCarrierDao.selectUsersByUserCode(userCode);
        if (CollectionUtils.isNotEmpty(entities)) {
            userContactCarrierDao.deleteByUserCode(userCode);
        }
        buildCarrier(userCode, carrier);
        return Response.ok().putData(true);
    }

    private void buildCarrier(String userCode, Carrier carrier) {
        UserContactCarrierEntity entity = new UserContactCarrierEntity();
        entity.setUserCode(userCode);
        entity.setCarrierUrl(carrier.getUrl());
        entity.setType(carrier.getCarrierType());
        entity.setStatus(carrier.getStatus());
        userContactCarrierDao.insert(entity);
    }

    @Override
    public Response<Boolean> addUserDeviceContact(String userCode, String deviceContactUrl) {
        return addUserDeviceContact(userCode, deviceContactUrl, AppCodeEnum.JYD);
    }

    @Override
    public Response<Boolean> addUserDeviceContact(String userCode, String deviceContactUrl, AppCodeEnum appCodeEnum) {
        if (StringUtils.isBlank(deviceContactUrl) || StringUtils.isBlank(userCode)) {
            return Response.error(UserErrorCodeEnum.PARAM_ERROR);
        }
        UserContactAddressBookEntity oldEntity = userContactAddressBookDao.selectByUserCode(userCode);
        if (oldEntity != null) {
            userContactAddressBookDao.deleteByUserCode(userCode);
        }
        UserContactAddressBookEntity entity = new UserContactAddressBookEntity();
        entity.setContactUrl(deviceContactUrl);
        entity.setUserCode(userCode);
        userContactAddressBookDao.insert(entity);
        return Response.ok().putData(true);
    }

    /**
     * 保持通讯录信息 新版
     *
     * @param userCode
     * @param deviceContactUrl
     * @param appEnum
     * @return boolean
     */
    @Override
    public Response<Boolean> addUserDeviceContact(String userCode, String deviceContactUrl, AppEnum appEnum) {
        return this.addUserDeviceContact(userCode, deviceContactUrl, appEnum.getAppId() + "");
    }

    /**
     * 保持通讯录信息 新版
     *
     * @param userCode
     * @param deviceContactUrl
     * @param appCode
     */
    @Override
    public Response<Boolean> addUserDeviceContact(String userCode, String deviceContactUrl, String appCode) {
        if (StringUtils.isBlank(deviceContactUrl) || StringUtils.isBlank(userCode) || StringUtils.isEmpty(appCode)) {
            return Response.error(UserErrorCodeEnum.PARAM_ERROR);
        }
        UserContactAddressBookEntity oldEntity = userContactAddressBookDao.selectByUserCode(userCode);
        if (oldEntity != null) {
            userContactAddressBookDao.deleteByUserCode(userCode);
        }
        UserContactAddressBookEntity entity = new UserContactAddressBookEntity();
        entity.setContactUrl(deviceContactUrl);
        entity.setUserCode(userCode);
        entity.setAppCode(appCode);
        entity.setUploadCount(oldEntity == null ? 0 : oldEntity.getUploadCount());
        userContactAddressBookDao.insert(entity);
        return Response.ok().putData(true);
    }

    @Override
    public Response<Boolean> addUserSmsInfo(String userCode, String deviceContactUrl, String smsUrl, String appCode) {
        if (StringUtils.isBlank(deviceContactUrl) || StringUtils.isBlank(userCode) || StringUtils.isEmpty(appCode)) {
            return Response.error(UserErrorCodeEnum.PARAM_ERROR);
        }
        UserContactAddressBookEntity oldEntity = userContactAddressBookDao.selectByUserCode(userCode);
        if (oldEntity != null) {
            userContactAddressBookDao.deleteByUserCode(userCode);
        }
        UserContactAddressBookEntity entity = new UserContactAddressBookEntity();
        entity.setContactUrl(deviceContactUrl);
        if (StringUtils.isNotBlank(smsUrl)) {
            entity.setSmsUrl(smsUrl);
            this.addSmsInfo(userCode, smsUrl, appCode);
        }
        entity.setUserCode(userCode);
        entity.setAppCode(appCode);
        entity.setUploadCount(oldEntity == null ? 0 : oldEntity.getUploadCount());
        userContactAddressBookDao.insert(entity);
        return Response.ok().putData(true);
    }

    @Override
    public Response<Boolean> addUserSmsInfo(String userCode, String smsUrl, String appCode) {
        if (StringUtils.isBlank(smsUrl) || StringUtils.isBlank(userCode) || StringUtils.isEmpty(appCode)) {
            return Response.error(UserErrorCodeEnum.PARAM_ERROR);
        }
        this.addSmsInfo(userCode, smsUrl, appCode);
        return Response.ok().putData(true);
    }

    private void addSmsInfo(String userCode, String smsUrl, String appCode) {
        UserSmsInfoEntity userSmsInfoEntity = userSmsInfoDao.selectByUserCode(userCode);
        if (userSmsInfoEntity != null) {
            userSmsInfoDao.deleteByUserCode(userCode);
        }
        UserSmsInfoEntity userSmsInfo = new UserSmsInfoEntity();
        userSmsInfo.setSmsUrl(smsUrl);
        userSmsInfo.setUserCode(userCode);
        userSmsInfo.setAppCode(appCode);
        userSmsInfo.setUploadCount(userSmsInfoEntity == null || userSmsInfoEntity.getUploadCount() == null ? 0 : userSmsInfoEntity.getUploadCount() + 1);
        userSmsInfoDao.insert(userSmsInfo);
    }

    @Override
    public Response<UserContactAddressBook> getUserDeviceContactByUserCode(String userCode) {
        if (StringUtils.isBlank(userCode)) {
            return Response.error(UserErrorCodeEnum.PARAM_ERROR);
        }
        UserContactAddressBookEntity oldEntity = userContactAddressBookDao.selectByUserCode(userCode);
        if (oldEntity == null) {
            return Response.ok();
        }
        UserContactAddressBook userContactAddressBook = new UserContactAddressBook();
        BeanUtils.copyProperties(oldEntity, userContactAddressBook);
        return Response.ok().putData(userContactAddressBook);
    }

    @Override
    public Response<UserContactSms> getUserDeviceSmsByUserCode(String userCode) {
        UserSmsInfoEntity userSmsInfoEntity = userSmsInfoDao.selectByUserCode(userCode);
        UserContactSms userContactSms = null;
        if (userSmsInfoEntity != null) {
            userContactSms = new UserContactSms();
            BeanUtils.copyProperties(userSmsInfoEntity, userContactSms);
        }
        return Response.ok().putData(userContactSms);
    }

    @Override
    public Response<List<UserContactSms>> getUserSmsListByPage(UserSmsPageQueryRO userSmsPageQueryRO) {
        if (userSmsPageQueryRO == null || userSmsPageQueryRO.getEndDate() == null) {
            return Response.error(BasicErrorCodeEnum.PARAM_NOT_COMPLETE, "param can not be empty");
        }
        List<UserSmsInfoEntity> userSmsInfoEntities = userSmsInfoDao.selectListByPage(userSmsPageQueryRO.getPage(), userSmsPageQueryRO.getEndDate());
        List<UserContactSms> userContactSmsList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(userSmsInfoEntities)) {
            for (UserSmsInfoEntity entity : userSmsInfoEntities) {
                UserContactSms userContactSms = new UserContactSms();
                BeanUtils.copyProperties(entity, userContactSms);
                userContactSmsList.add(userContactSms);
            }
        }
        return Response.ok().putData(userContactSmsList);
    }

    /**
     * 获取通讯录信息
     *
     * @param userCode
     */
    @Override
    public Response<UserContactAddressBook> getUserDeviceContactByUserCodeAndAppCode(String userCode, AppEnum appEnum) {
        if (StringUtils.isBlank(userCode) || appEnum == null) {
            return Response.error(UserErrorCodeEnum.PARAM_ERROR);
        }
        UserContactAddressBookEntity oldEntity = userContactAddressBookDao.selectByUserCodeAndAppCode(userCode, appEnum.getAppId() + "");
        if (oldEntity == null) {
            return Response.ok();
        }
        UserContactAddressBook userContactAddressBook = new UserContactAddressBook();
        BeanUtils.copyProperties(oldEntity, userContactAddressBook);
        return Response.ok().putData(userContactAddressBook);
    }

    /**
     * 获取通讯录信息
     *
     * @param userCode
     */
    @Override
    public Response<List<UserContactAddressBook>> getUserDeviceContactListByUserCode(String userCode) {
        if (StringUtils.isBlank(userCode)) {
            return Response.error(UserErrorCodeEnum.PARAM_ERROR);
        }
        List<UserContactAddressBookEntity> list = userContactAddressBookDao.selectFirstAndLastByUserCode(userCode);
        if (CollectionUtils.isEmpty(list)) {
            return Response.ok();
        }
        List<UserContactAddressBook> userContactAddressBookList = list.stream().map(item -> {
            UserContactAddressBook userContactAddressBook = new UserContactAddressBook();
            BeanUtils.copyProperties(item, userContactAddressBook);
            return userContactAddressBook;
        }).collect(Collectors.toList());
        return Response.ok().putData(userContactAddressBookList);
    }

    @Override
    public Response<List<UserContactAddressBook>> getUserDeviceContactListByPage(UserContactAddressBookPageQueryRO userContactAddressBookPageQueryRO) {
        if (userContactAddressBookPageQueryRO == null || userContactAddressBookPageQueryRO.getEndDate() == null) {
            return Response.error(BasicErrorCodeEnum.PARAM_NOT_COMPLETE, "param can not be empty");
        }
        List<UserContactAddressBookEntity> userContactAddressBookEntities = userContactAddressBookDao.selectListByPage(userContactAddressBookPageQueryRO.getPage(), userContactAddressBookPageQueryRO.getEndDate());
        List<UserContactAddressBook> userContactAddressBooks = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(userContactAddressBookEntities)) {
            for (UserContactAddressBookEntity entity : userContactAddressBookEntities) {
                UserContactAddressBook userContactAddressBook = new UserContactAddressBook();
                BeanUtils.copyProperties(entity, userContactAddressBook);
                userContactAddressBooks.add(userContactAddressBook);
            }
        }
        return Response.ok().putData(userContactAddressBooks);
    }

    @Override
    public Response<Boolean> updateUserDeviceContact(String userCode, String deviceContactUrl, String smsUrl) {
        if (StringUtils.isBlank(userCode) && (StringUtils.isBlank(smsUrl) || StringUtils.isBlank(deviceContactUrl))) {
            return Response.error(UserErrorCodeEnum.PARAM_ERROR);
        }
        if (StringUtils.isBlank(deviceContactUrl)) {
            deviceContactUrl = null;
        }
        UserContactAddressBookEntity oldEntity = userContactAddressBookDao.selectByUserCode(userCode);
        if (oldEntity == null) {
            UserContactAddressBookEntity entity = new UserContactAddressBookEntity();
            entity.setContactUrl(deviceContactUrl);
            entity.setSmsUrl(smsUrl);
            entity.setUserCode(userCode);
            userContactAddressBookDao.insert(entity);
            return Response.ok().putData(true);
        }
        int updateRow = userContactAddressBookDao.updateByUserCode(userCode, deviceContactUrl, smsUrl, oldEntity.getId());
        return Response.ok().putData(updateRow > 0);
    }

    @Override
    public Response<Boolean> updateUserDeviceContact(String userCode, String deviceContactUrl) {
        if (StringUtils.isBlank(userCode) || StringUtils.isBlank(deviceContactUrl)) {
            return Response.error(UserErrorCodeEnum.PARAM_ERROR);
        }
        UserContactAddressBookEntity oldEntity = userContactAddressBookDao.selectByUserCode(userCode);
        int updateRow = userContactAddressBookDao.updateByUserCode(userCode, deviceContactUrl, null, oldEntity.getId());
        return Response.ok().putData(updateRow > 0);
    }

    @Override
    public Response<Boolean> addUserEmergencyContact(String userCode, UserEmergencyContact userEmergencyContact) {
        if (userEmergencyContact == null) {
            return Response.ok().putData(true);
        }
        UserContactEmergencyEntity oldEntity = userContactEmergencyDao.selectByUserCode(userCode);
        if (oldEntity != null) {
            return updateUserEmergencyContact(userCode, userEmergencyContact);
        }
        UserContactEmergencyEntity userEmergenceContactEntity = convertEmergencyToEntity(userEmergencyContact);
        userEmergenceContactEntity.setUserCode(userCode);
        userContactEmergencyDao.insert(userEmergenceContactEntity);
        return Response.ok().putData(true);
    }

    @Override
    public Response<Boolean> updateUserEmergencyContact(String userCode, UserEmergencyContact userEmergencyContact) {
        UserContactEmergencyEntity update = convertEmergencyToEntity(userEmergencyContact);
        update.setUserCode(userCode);

        int updateRow = userContactEmergencyDao.updateByUserCode(userCode, update);
        return Response.ok().putData(updateRow > 0);
    }

    private UserContactEmergencyEntity convertEmergencyToEntity(UserEmergencyContact userEmergencyContact) {
        UserFamilyContact userFamilyContact = userEmergencyContact.getUserFamilyContact();
        UserFriendContact userFriendContact = userEmergencyContact.getUserFriendContact();

        UserContactEmergencyEntity update = new UserContactEmergencyEntity();

        update.setUserCode(userEmergencyContact.getUserCode());
        if (userFamilyContact != null) {
            update.setFamilyType(userFamilyContact.getUserContactFamilyTypeEnum().getType());
            update.setFamilyName(getCommenName(userFamilyContact.getName()));
            update.setFamilyMobile(userFamilyContact.getMobile());
            update.setFamilyContactName(getCommenName(userFamilyContact.getContactName()));
        }
        if (userFriendContact != null) {
            update.setFriendType(userFriendContact.getUserContactFriendTypeEnum().getType());
            update.setFriendName(getCommenName(userFriendContact.getName()));
            update.setFriendMobile(userFriendContact.getMobile());
            update.setFriendContactName(getCommenName(userFriendContact.getContactName()));
        }
        return update;
    }

    @Override
    public Response<UserSocialContact> getUserSocialContactByUserCode(String userCode) {
        UserContactCarrierEntity carrierEntity = userContactCarrierDao.selectByUserCode(userCode);
        Carrier carrier = null;
        if (carrierEntity != null) {
            carrier = new Carrier(carrierEntity.getCarrierUrl(), carrierEntity.getType()
                    , carrierEntity.getGmtModified(), carrierEntity.getStatus(), carrierEntity.getUserCode());
        }

        UserContactAddressBookEntity addressBookEntity = userContactAddressBookDao.selectByUserCode(userCode);

        UserContactEmergencyEntity emergencyEntity = userContactEmergencyDao.selectByUserCode(userCode);

        UserEmergencyContact emergencyContact = null;
        if (emergencyEntity != null) {
            UserContactFamilyTypeEnum familyType = UserContactFamilyTypeEnum.getEnumByType(emergencyEntity.getFamilyType());
            UserFamilyContact familyContact = new UserFamilyContact(emergencyEntity.getFamilyName(),
                    emergencyEntity.getFamilyContactName(), emergencyEntity.getFamilyMobile(), familyType);
            UserContactFriendTypeEnum friendTypeEnum = UserContactFriendTypeEnum.getEnumByType(emergencyEntity.getFriendType());
            UserFriendContact friendContact = new UserFriendContact(emergencyEntity.getFriendName(),
                    emergencyEntity.getFriendContactName(), emergencyEntity.getFriendMobile(), friendTypeEnum);
            emergencyContact = new UserEmergencyContact(userCode, familyContact, friendContact);
        }

        UserSocialContact contact = new UserSocialContact();
        contact.setCarrier(carrier);
        if (addressBookEntity != null) {
            contact.setDeviceContact(addressBookEntity.getContactUrl());
            contact.setGmtCreate(addressBookEntity.getGmtCreate());
        }
        contact.setUserEmergencyContact(emergencyContact);
        return Response.ok().putData(contact);
    }

    @Override
    public Response<List<Carrier>> getCarriers(String userCode) {
        List<UserContactCarrierEntity> entities = userContactCarrierDao.selectUsersByUserCode(userCode);
        if (CollectionUtils.isEmpty(entities)) {
            return Response.ok().putData(Lists.newArrayList());
        }
        List<Carrier> carriers = entities.stream()
                .map(en ->
                        new Carrier(en.getCarrierUrl(), en.getType()
                                , en.getGmtModified(), en.getStatus(), en.getUserCode())).collect(Collectors.toList());
        return Response.ok().putData(carriers);
    }

    @Override
    public Response<List<Carrier>> getCarriersByStatus(Integer status) {
        List<UserContactCarrierEntity> entities = userContactCarrierDao.selectUsersByStatus(status);
        if (CollectionUtils.isEmpty(entities)) {
            return Response.ok().putData(Lists.newArrayList());
        }
        List<Carrier> carriers = entities.stream()
                .map(en ->
                        new Carrier(en.getCarrierUrl(), en.getType()
                                , en.getGmtModified(), en.getStatus(), en.getUserCode())).collect(Collectors.toList());
        return Response.ok().putData(carriers);
    }

    @Override
    public Response<Boolean> checkUserEmergencyContactOccupied(String userCode, String mobile) {
        List<UserContactEmergencyEntity> listByFamily = userContactEmergencyDao.selectByFamilyMobile(userCode, mobile);
        List<UserContactEmergencyEntity> listByFriend = userContactEmergencyDao.selectByFriendMobile(userCode, mobile);
        if (CollectionUtils.isNotEmpty(listByFamily) || CollectionUtils.isNotEmpty(listByFriend)) {
            return Response.ok().putData(Boolean.TRUE);
        }

        return Response.ok().putData(Boolean.FALSE);
    }

    private String getCommenName(String name) {
        if (StringUtils.isBlank(name)) {
            return "";
        }
        String reg = "[^(A-Za-z0-9\\s*)]";
        Pattern pat = Pattern.compile(reg);
        Matcher mat = pat.matcher(name);
        String repickStr = mat.replaceAll(" ");
        System.out.println(repickStr);

        return repickStr;
    }
}
